import React, { useEffect, useState, useLayoutEffect } from "react";
import { Table, Button, Input, Row, Col, Space } from "antd";
import type { TableProps } from "antd";
import { fetchData, queryData, delData } from "../../api";
import { box } from "../../mobx/box";
import { observer } from "mobx-react-lite";
import type MyData from "./type";
const { Search } = Input;

const MyTable: React.FC = () => {
  useEffect(() => {
    console.log("useEffect");
    getData();
  }, []);
  useLayoutEffect(() => {
    console.log("useLayoutEffect");
  }, []);

  const [data, setData] = useState<MyData[]>([]);
  const [searchValue, setSearchValue] = useState<string>();

  const getData = async () => {
    try {
      let data: any = await fetchData();
      data.forEach((item: MyData) => {
        item.key = item.id;
      });
      setData(data);
    } catch (err) {}
  };
  const search = async (value: string) => {
    if (value === "") {
      await getData();
    } else {
      let data: any = await queryData(value);
      console.log(data);
      if (data.id) {
        data.key = data.id;
        setData([data]);
      }
    }
  };
  const del = async (record: MyData) => {
    let res = await delData(record.id);
    console.log(res);
    getData();
  };
  const columns: TableProps<MyData>["columns"] = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "UserId",
      dataIndex: "userId",
      key: "userId",
    },
    {
      title: "Body",
      dataIndex: "body",
      key: "body",
    },
    {
      title: "Title",
      dataIndex: "title",
      key: "title",
    },
    {
      title: "Action",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary">编辑</Button>
          <Button
            danger
            onClick={() => {
              del(record);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];
  return (
    <>
      <Row style={{ margin: "10px 0" }}>
        <Col span={8}>
          <Button
            loading={box.loading}
            onClick={() => {
              getData();
              setSearchValue("");
            }}
          >
            刷新
          </Button>
        </Col>
        <Col span={8}></Col>
        <Col span={8}>
          <Search
            value={searchValue}
            placeholder="搜索内容"
            loading={box.loading}
            enterButton
            onSearch={search}
            onChange={(e)=>{
              setSearchValue(e.target.value)
            }}
          />
        </Col>
      </Row>

      <Table columns={columns} dataSource={data} bordered />
    </>
  );
};

export default observer(MyTable);
